#!/bin/bash

# @License EPL-1.0 <http://spdx.org/licenses/EPL-1.0>
##############################################################################
# Copyright (c) 2015 The Linux Foundation and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
##############################################################################

ARTIFACT_DIR=".sign-artifacts"
SIGNATURES_DIR="gpg-signatures"


function print_usage {
    echo "Usage: $0 sign <url>"
    echo ""
    echo "    sign   : Downloads and Signs artifacts from Nexus"
}


# Downloads artifacts from a Nexus URL and creates gpg signatures for them
# and copies the signatures to a separate directory.
function sign {
    echo "Signing artifacts..."

    if [ -d "$ARTIFACT_DIR" ]; then
        echo "$ARTIFACT_DIR directory exists. Clearing..."
        rm -rf $ARTIFACT_DIR
    fi

    mkdir $ARTIFACT_DIR
    cd $ARTIFACT_DIR

    echo "Fetching artifacts from $URL"
    # Fetch Artifacts
    wget --recursive --execute robots=off --no-parent --quiet \
        --no-host-directories --cut-dirs=3 \
        $URL

    # Remove files that don't need signing
    find . -type f \
            -name "*.asc" \
            -o -name "*.sha1" \
            -o -name "*.md5" \
            -o -name "_maven.repositories*" \
            -o -name "_remote.repositories*" \
            -o -name "maven-metadata-local.xml*" \
            -o -name "maven-metadata.xml*" \
            -o -name "index.html*" | xargs rm

    for f in `find . -type f ! -name "*.asc" ! -name "*.sha1" ! -name "*.md5"`
    do
        echo "Signing $f"
        gpg2 --batch -abq $f
    done

    cd ..

    if [ -d "$SIGNATURES_DIR" ]; then
        echo "$SIGNATURES_DIR directory exists. Clearing..."
        rm -rf $SIGNATURES_DIR
    fi

    rsync -avz --include '*/' --include '*.asc' --exclude '*' \
           "${ARTIFACT_DIR}/org" "${SIGNATURES_DIR}"
}


if [ -z "$2" ]; then
    print_usage
    exit 1
fi

MODE=$1
URL=$2

if [ "$MODE" == "sign" ]; then
    sign
else
    echo "ERROR: Invalid mode."
    print_usage
    exit 1
fi
